package uk.ac.durham.tel.synergynet.covanto.project.model;

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;

import uk.ac.durham.tel.commons.model.PropertySupportObject;

@XmlRootElement
public class ProjectInfo extends PropertySupportObject {
	private IProject projectResource;
	public static final String PROP_IS_PROJECT_RESOURCE_OPENED = "isProjectResourceOpened";
	private boolean isProjectResourceOpened;
	private IResourceChangeListener projectResourceChangeListener = new IResourceChangeListener() {
		@Override
		public void resourceChanged(IResourceChangeEvent event) {
			try {
				event.getDelta().accept(new IResourceDeltaVisitor() {
					public boolean visit(IResourceDelta delta) throws CoreException {
						if (delta.getResource() == projectResource) {
							IProject changedProjectResource = ((IProject)delta.getResource());
							if (delta.getKind() == IResourceDelta.CHANGED) {
								if (changedProjectResource.isOpen() && !ProjectInfo.this.isProjectResourceOpened()) 
									ProjectInfo.this.setProjectResourceOpened(true);
								if (!changedProjectResource.isOpen() && ProjectInfo.this.isProjectResourceOpened())
									ProjectInfo.this.setProjectResourceOpened(false);
							} 
						}
						return true;
					}
				});
			} catch (CoreException ex) {
				//
			}
		}
	};
	
	
	public ProjectInfo(IProject projectResource) {
		addResourceChangeListener();
		this.projectResource = projectResource;
		if (projectResource.isOpen())
			setProjectResourceOpened(true);
		else setProjectResourceOpened(false);
	}

	@XmlTransient
	public IProject getProjectResource() {
		return projectResource;
	}

	public void dispose() {
		removeResourceChangeListener();
	}
	
	private void removeResourceChangeListener() {
		ResourcesPlugin.getWorkspace().removeResourceChangeListener(projectResourceChangeListener);
	}

	private void addResourceChangeListener() {
		ResourcesPlugin.getWorkspace().addResourceChangeListener(projectResourceChangeListener, IResourceChangeEvent.POST_CHANGE);
	}

	public void setProjectResourceOpened(boolean isProjectResourceOpened) {
		firePropertyChange(PROP_IS_PROJECT_RESOURCE_OPENED, this.isProjectResourceOpened, this.isProjectResourceOpened = isProjectResourceOpened);
	}

	public boolean isProjectResourceOpened() {
		return isProjectResourceOpened;
	}
}
